#pragma once
#include "Socket.hpp"
#include "Log.hpp"
#include <sys/epoll.h>
using namespace MyLogModule;
using namespace MySocketModule;

const int gdefaultfd = -1;
#define ARRAY_SIZE 64

class EpollServer
{
private:
    std::unique_ptr<Socket> _listen_socket;
    int16_t _port;
    bool _isrunning;
    int _epollfd;       //epoll模型所对应的fd
    struct epoll_event *_ready_events;  //接收就绪事件的数组

// typedef union epoll_data {
//     void    *ptr;
//     int      fd;
//     uint32_t u32;
//     uint64_t u64;
// } epoll_data_t;

// struct epoll_event {
//     uint32_t     events;    /* Epoll events */
//     epoll_data_t data;      /* User data variable */
// };
public:
    EpollServer(int16_t port)
        : _port(port)
        , _listen_socket(make_unique<TcpSocket>())
        ,_ready_events(new epoll_event[ARRAY_SIZE])
    {
        
    }

    ~EpollServer()
    {
    }

    void Init()
    {
        _listen_socket->BuildTcpSocketMethod(_port);
        //1. epoll模型创建成功
        _epollfd = epoll_create(128);
        //ince Linux 2.6.8, the size argument is ignored,参数随便填一个 正整数！
        if(_epollfd < 0)
        {
            LOG(LogGrade::ERROR) << "epoll_create fail";
            exit(EPOLL_CREATE_ERR);
        }
        LOG(LogGrade::DEBUG) << "epoll_create success,_epollfd:" << _epollfd;
        //2. 将listen_socket添加到模型中
        struct epoll_event ev;
        ev.data.fd = _listen_socket->GetSockfd();
        ev.events = EPOLLIN;
        int n = epoll_ctl(_epollfd,EPOLL_CTL_ADD,_listen_socket->GetSockfd(),&ev);
        if(n < 0)
        {
            LOG(LogGrade::ERROR) << "epoll_ctl fail";
            exit(EPOLL_CTRL_ERR);
        }
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {

            int timeout = 1000;
            //3. 等待
            int n = epoll_wait(_epollfd, _ready_events, ARRAY_SIZE, timeout);
            switch (n)
            {
            case 0:
                cout << "time out," << endl;
                break;
            case -1:
                cout << "select error" << endl;
                break;
            default:
                cout << "有事件就绪了....." << endl;
                //将就绪事件的个数传递，不做无效的遍历
                Dispatcher(n);
                break;
            }
        }
        _isrunning = false;
    }

    void Accepter()
    {
        InetAddr client;
        // 此时accept就不会阻塞了
        int newfd = _listen_socket->AcceptOrDie(&client);
        if (newfd < 0)
            return;
        else
        {
            //将fd添加到epoll模型中
            struct epoll_event ev;
            ev.data.fd = newfd;
            ev.events = EPOLLIN;
            int n = epoll_ctl(_epollfd, EPOLL_CTL_ADD, newfd, &ev);
            if(n < 0)
            {
                LOG(LogGrade::ERROR) << "epoll_ctl fail";
                close(newfd);
            }
            LOG(LogGrade::ERROR) << "epoll_ctl success";
        }
    }

    void Recver(int fd)
    {
        char buf[1024];
        size_t n = recv(fd, buf, sizeof(buf) - 1, 0);   //bug
        if (n > 0)
        {
            buf[n] = 0;
            cout << "Client# " << buf << endl;
            string str = "Echo#";
            str += buf;
            send(fd,str.c_str(),str.size(), 0);   //bug
        }
        else if (n == 0)
        {
            LOG(LogGrade::DEBUG) << "客户端退出了,fd:" << fd;

            //epoll_ctl规定，传入的fd必须是非法的，因此需要先移除，后关闭
            int n = epoll_ctl(_epollfd, EPOLL_CTL_DEL, fd, nullptr);
            if(n < 0)
            {
                LOG(LogGrade::ERROR) << "epoll_ctl fail";
                exit(EPOLL_CTRL_ERR);
            }
            close(fd);  //后关闭
        }
        else
        {
            LOG(LogGrade::DEBUG) << "客户端读取出错了,fd:" << fd;
            int n = epoll_ctl(_epollfd, EPOLL_CTL_DEL, fd, nullptr);
            if(n < 0)
            {
                LOG(LogGrade::ERROR) << "epoll_ctl fail";
                exit(EPOLL_CTRL_ERR);
            }
            //epoll_ctl规定，传入的fd必须是非法的，因此需要先移除，后关闭
            close(fd);
        }
    }

    void Dispatcher(int readynum)
    {
        //数组中全是就绪事件，没有无效的遍历
        for (int i = 0; i < readynum;i++)
        {
            // 判断是否是listen_socket
            if (_ready_events[i].data.fd == _listen_socket->GetSockfd())
            {
                // 判断listen_socket是否在返回的事件中
                if (_ready_events[i].events & EPOLLIN)
                {
                    Accepter();
                }
            }
            else
            {
                // 普通fd就绪了
                if (_ready_events[i].events & EPOLLIN)
                {
                    //读事件就绪
                    Recver(_ready_events[i].data.fd);  //进行IO
                }
            }
        }
    }
};